package com.example.review.Util;

import com.google.gson.Gson;

import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public abstract class RetrofitUtil {
    private Call<ResponseBody> call;
    public RetrofitUtil(Call<ResponseBody> call){
        this.call = call;
    }

    //初始化Retrofit
    public static Retrofit initialize(String url){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .build();
        return retrofit;
    }

    //如果是post请求需要参数放入参数就调用这个方法
    public static RequestBody initializeParameter(Map map){
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), gson.toJson(map));
        return body;
    }

    //发送请求
    public void sendRequest(){
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                onFinish(call, response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                onError(call, t);
            }
        });
    }

    //访问成功的回调
    public abstract void onFinish(Call<ResponseBody> call, Response<ResponseBody> response);
    //访问失败的回调
    public abstract void onError(Call<ResponseBody> call, Throwable t);
}
